package com.jt.www.biz.order_pc.controller;

import com.alibaba.fastjson.JSONObject;
import com.jt.www.admin.order_pc.service.ApplicationFormService;
import com.jt.www.biz.order_pc.service.EndorseService;
import com.jt.www.biz.order_pc.service.PreviewService;
import com.jt.www.model.param.endorse.AppDetailProParam;
import com.jt.www.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Api(value = "投保单/批单预览", tags = {"INS-PREVIEW-API"}, description = "批单预览")
@Controller
@RequestMapping("/ins/preview")
public class InsPreviewController {

    public static final Logger log = LoggerFactory.getLogger(InsPreviewController.class);
    @Autowired
    EndorseService endorseService;
    @Autowired
    PreviewService previewService;
    @Autowired
    ApplicationFormService applicationFormService;

    //  预览接口   确认  不用转换pdf
    @ApiOperation(value = "批单预览", notes = "批单预览", httpMethod = "POST")
    @PostMapping(value = "/{flag}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public String endorsePreview(@ApiParam(value = "批单信息", required = true) @RequestBody String data,
                                 @ApiParam(value = "标志:1-批增，2-批减，3-人员替换，4-一般性批改,5-批退", required = true) @PathVariable String flag, Model model) {

        log.info(DateUtils.getCurrentTime() + ",进入批单预览接口，入参" + data + "," + flag);
        JSONObject obj = getEndor(data, flag);
        model.addAttribute("endor", obj);
        if ("1".equals(flag) || "2".equals(flag)) {
            return "addAndLess";
        } else if ("4".equals(flag)) {
            return "general";
        } else if ("3".equals(flag)) {
            return "replace";
        } else if ("5".equals(flag)) {
            return "refund";
        }

        return null;
    }

    public JSONObject getEndor(String data, String flag) {
        JSONObject obj = JSONObject.parseObject(data);
        if ("3".equals(flag)) {
            // 造一个集合  存放 两类数据
            List<Map<String, String>> resultList = new ArrayList<>();
            // 需要去调用接口  String replaceFileId, String originFileId
            String replaceFileId = obj.getString("replaceFileId");
            String originFileId = obj.getString("originFileId");
            String policyType = obj.getString("policyType");
            Map map = endorseService.replaceDetail(replaceFileId, originFileId, Integer.valueOf(policyType));
            Map<String, List<Map<String, String>>> replaceMap = (Map) map.get("replace");
            Map<String, List<Map<String, String>>> originMap = (Map) map.get("origin");
            Collection<List<Map<String, String>>> replaceValues = replaceMap.values();
            Collection<List<Map<String, String>>> originValues = originMap.values();
            Iterator<List<Map<String, String>>> replaceIterator = replaceValues.iterator();
            Iterator<List<Map<String, String>>> originIterator = originValues.iterator();

            while (replaceIterator.hasNext()) {
                List<Map<String, String>> replaceList = replaceIterator.next();
                List<Map<String, String>> originList = originIterator.next();
                int size = replaceList.size();
                for (int i = 0; i < size; i++) {
                    Map<String, String> replace = replaceList.get(i);
                    Map<String, String> origin = originList.get(i);
                    Map<String, String> resultMap = new HashMap<>();
                    resultMap.put("replaceName", replace.get("name"));
                    resultMap.put("replaceSex", replace.get("sex"));
                    resultMap.put("replaceCertificateType", replace.get("certificateType"));
                    resultMap.put("replaceCardNo", replace.get("cardNo"));
                    resultMap.put("originName", origin.get("name"));
                    resultMap.put("originSex", origin.get("sex"));
                    resultMap.put("originCertificateType", origin.get("certificateType"));
                    resultMap.put("originCardNo", origin.get("cardNo"));
                    resultList.add(resultMap);
                }
            }
            obj.put("resultList", resultList);
        }
        return obj;
    }


    //  预览接口   转换pdf
    @ApiOperation(value = "批单下载", notes = "批单下载", httpMethod = "POST")
    @PostMapping(value = "/downloadEndorPdf")
    public String endorsePdfPreview(HttpServletRequest request, HttpServletResponse response, String data,
                                    String flag, Model model) {

        log.info(DateUtils.getCurrentTime() + ",进入批单下载pdf接口，入参" + data + "," + flag);
        JSONObject obj = getEndor(data, flag);
        WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale());
        ctx.setVariable("endor", obj);
        try {
            endorseService.downEndorPdf(ctx, flag, model, request, response);
        } catch (Exception e) {
            log.error("生成投保单pdf失败,请稍后重试");
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "投保单预览", notes = "投保单预览", httpMethod = "GET")
    @GetMapping(value = "/appForm")
    public String appForm(AppDetailProParam param, Model model) {
        String findCode = "appForm_" + System.currentTimeMillis();
        try {
            log.info("投保单预览{}开始,投保单号{}", findCode, param.getAppCode());
            return previewService.appForm(param, model, findCode);
        } catch (Exception e) {
            log.error("投保单预览{}失败,请稍后重试 投保单号{}", findCode, param.getAppCode());
            e.printStackTrace();
        }
        return null;
    }


    @ApiOperation(value = "下载投保单PDF", notes = "下载投保单PDF", httpMethod = "GET")
    @GetMapping(value = "/downAppFromPdf")
    public void downAppFromPdf(AppDetailProParam param, Model model, HttpServletRequest request, HttpServletResponse response) {
        try {
            applicationFormService.downAppFormPdf(param, model, request, response);
        } catch (Exception e) {
            log.error("生成投保单pdf失败,请稍后重试");
            e.printStackTrace();
        }
    }

    /**
     * 业管推送和结算状态查询
     *
     * @param policyNo
     * @param model
     * @return
     */
    @ApiOperation(value = "业管推送和结算状态查询", notes = "业管推送和结算状态查询", httpMethod = "GET")
    @GetMapping(value = "/bms/pushStatus")
    public String pushStatus(String policyNo, String endorsementNo, Model model) {
        String findCode = "pushStatus_" + System.currentTimeMillis();
        try {
            log.info("{} 业管推送和结算状态查询开始 保单号->{}，批单号->{}", findCode, policyNo, endorsementNo);

            if (StringUtils.isBlank(policyNo) && StringUtils.isBlank(endorsementNo)) {
                log.info("{} 业管推送和结算状态查询结束 保单号、批单号均为空!", findCode);
                return null;
            }

            return previewService.pushStatus(policyNo, endorsementNo, model, findCode);
        } catch (Exception e) {
            log.error("{} 业管推送和结算状态查询失败,请稍后重试 保单号->{}", findCode, policyNo);
            e.printStackTrace();
        }
        return null;
    }

}
